package com.xuanwei.core.util;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class GenerateOrderNO {

    /**
     * 锁对象
     */
    private static Object lockObj = "lockerOrder";
    /**
     * 订单号生成计数器
     */
    private static AtomicInteger orderNumCount = new AtomicInteger(0);
    /**
     * 每毫秒生成订单号数量最大值
     */
    private static int maxPerMSECSize = 1000;

    /**
     * 生成非重复订单号，理论上限1毫秒1000个，可扩展
     */
    public static String makeOrderNum() {

        synchronized (lockObj) {
            // 取系统当前时间作为订单号变量前半部分，精确到毫秒
            long nowLong = Long
                    .parseLong(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
            // 计数器到最大值归零，可扩展更大
            if (orderNumCount.get() > maxPerMSECSize) {
                orderNumCount.set(0);
            }

            return ""+nowLong + orderNumCount.incrementAndGet();
        }
    }

}
